<html>
<head>

<title>Groovy Goodness: Getting the Tail of a List</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Getting the Tail of a List</h3>

<div class="post">
<p>Groovy adds several methods to the <code>List</code> interface. In this post we look at the <code>head()</code> and <code>tail()</code> methods. The <code>head()</code> method returns the first element of the list, and the <code>tail()</code> returns the rest of the elements in the list after the first element. The following code snippet shows a simple recursive method to reverse a list.</p>
<pre class="brush:groovy">
def list = [1, 2, 3, 4]

def reverse(l) {
    if (l.size() == 0) {
        []
    } else {
        reverse(l.tail()) + l.head()
    }
}

assert [4, 3, 2, 1] == reverse(list)

// For the same result we can of course use the List.reverse() method,
// but then we didn't learn about tail() and head() ;-)
assert [4, 3, 2, 1] == list.reverse()
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>